#include "qNormativkorekcija.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include "chelperclass.h"
#include <QDesktopWidget>


QNormativKorekcija::QNormativKorekcija(QWidget *parent)
	: QMyBaseFormWidget(parent)
    , selRow(-1)
    , textId("")
    , proizvodID("")
    ,artikal_id(0)
    , pItemDelegate(0)
    , editorOpen(0)
	, m_bProizvod(false)
{
    ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.lineEdit->setFocus();
    ui.lineEdit->setText("");
	ui.lineEdit->setStyleSheet("background-color: yellow");
    
    ui.lineEdit_2->setText("");
	ui.lineEdit->installEventFilter(this);
	ui.lineEdit_2->installEventFilter(this);
	ui.lineEdit_3->installEventFilter(this);
	ui.lineEdit_4->installEventFilter(this);
	ui.lineEdit_5->installEventFilter(this);
    ui.dateTimeEdit->installEventFilter(this);

	connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton_clicked()));
    connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton_2_clicked()));
    connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
    connect(ui.lineEdit_4, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));

    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));

    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);

    model = new QStandardItemModel(0,8);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Реф."));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Катал. број"));
    model->setHeaderData( 6, Qt::Horizontal, trUtf8("Цена"));
    model->setHeaderData( 7, Qt::Horizontal, trUtf8("Количина"));
	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
}

QNormativKorekcija::~QNormativKorekcija()
{

}
void QNormativKorekcija::pressEscape()
{
    if (ui.lineEdit_2->hasFocus())
    {
        ui.pushButton_4->setFocus();
        ui.pushButton_4->setChecked(true);
    }
    else
    {
        emit closeW();
    }
}
void QNormativKorekcija::on_pushButton_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit->text());
		m_bProizvod = true;
    }
    else
    {
        ui.lineEdit_2->setFocus();
    }
}

void QNormativKorekcija::setFocusLine()
{
	ui.lineEdit->setFocus();
}
void QNormativKorekcija::setKomintent(QString text, QString textName)
{
	ui.lineEdit->setText(textName);
	proizvodID = text;
}

void QNormativKorekcija::setArtikli(QString text, QString textName)
{
    if (!m_bProizvod)
    {
        ui.lineEdit_2->setText(textName);
        textId = text;
        artikal_id = text.toInt();

        QSqlQuery query;
        query.prepare("select edm from artikli where id = :id");
        query.bindValue(":id", artikal_id);	
        query.exec();
        query.next();
        ui.lineEdit_3->setText(query.value(0).toString());
    }
    else
    {
        ui.lineEdit->setText(textName);
        artikal_id = text.toInt();

        QSqlQuery query;
        query.prepare("select id from artikli where id = :id");
        query.bindValue(":id", artikal_id);	
        query.exec();
        query.next();
        proizvodID = query.value(0).toString();
    }
}

void QNormativKorekcija::setFocusLine2()
{
	ui.lineEdit_2->setFocus();
}

void QNormativKorekcija::on_pushButton_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
		m_bProizvod = false;
    }
    else
    {
        ui.lineEdit_4->setFocus();
    }
}



void QNormativKorekcija::on_pushButton_3_clicked()
{
	CHelperClass hclass(this);
	if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_2->setFocus();
		return;
	}

	QLocale loc;
	if(textId.toInt() == -1)
	{
		return;
	}

	//m_id = textId.toInt();

	QString temp = "select id, sifra, artikal, edm from artikli where id =";
	temp += textId;
	QSqlQuery query(temp);
	QString country1 = "";
	QString country2 = "";
	QString country3 = "";
	QString country4 = "";
	while (query.next()) 
	{
		country1 = query.value(query.record().indexOf("id")).toString();
		country2 = query.value(query.record().indexOf("sifra")).toString();
		country3 = query.value(query.record().indexOf("artikal")).toString();
		country4 = query.value(query.record().indexOf("edm")).toString();
		//        ui.lineEdit->setText(country1);
	}

	int row = model->rowCount();

	QStandardItem *item = new QStandardItem(country1);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(0, 50);
	model->setItem(row, 0, item);

	item = new QStandardItem(country2);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(1, 50);
	model->setItem(row, 1, item);

	item = new QStandardItem(country3);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 2, item);

	item = new QStandardItem(country4);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 3, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat(), 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(6, 80);
	model->setItem(row, 4, item);

	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();

	ui.lineEdit_2->selectAll();
	ui.lineEdit_3->setText("");
	ui.lineEdit_4->setText("");
	ui.lineEdit_2->setFocus();
	textId = "-1";
}
void QNormativKorekcija::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
	selRow = modelX.row();
    editorOpen = false;
    emit closeCell();
}

void QNormativKorekcija::on_pushButton_6_clicked()
{
	model->removeRow(selRow);
}
void QNormativKorekcija::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}
void QNormativKorekcija::init(int id)
{
    QLocale loc;
    if(id == -1)
    {
        return;
    }
    m_id = id;
    ui.lineEdit_5->setText(QString::number(id, 10));
	QString temp1 = 
		"SELECT id_proizvod, sifra, artikal, edm "
		"FROM proizvodi_sostav "
		"LEFT JOIN artikli ON proizvodi_sostav.id_proizvod = artikli.id "
		"WHERE proizvodi_sostav.id_proizvod = "; 
	temp1 += QString::number(id, 10);
	temp1 += " GROUP BY id_proizvod limit 20";
		
    
    QSqlQuery query1(temp1);
    while (query1.next())
    {
        ui.lineEdit->setText(query1.value(2).toString().isEmpty() ? "" : query1.value(2).toString());
        proizvodID = query1.value(0).toString();
        QString a = query1.value(0).toString();
    }
	int r = 0;
	int c = 5;
	int fieldNo[5];
	QString country[5];
	int colWidth[] = {40, 80, 180, 60, 100};
	QString colName[] = {"id", "sifra", "artikal", "edm", "kolicina"};
	QString temp = 
		"SELECT artikli.id, sifra, artikal, edm, kolicina "
		"FROM proizvodi_sostav "
		"LEFT JOIN artikli ON proizvodi_sostav.id_artikal = artikli.id "
		"WHERE id_proizvod = "+ proizvodID +" "
		;

	QSqlQuery query(temp);
	model = new QStandardItemModel(r,c);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм"));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Кол."));

	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
	header->show();
	int row = 0;
	while (query.next()) 
	{
		for (int i = 0; i < c; i++)
		{
			fieldNo[i] = query.record().indexOf(colName[i]);
			QStandardItem *item = new QStandardItem(query.value(fieldNo[i]).toString());
			if (i == 4)
			{
				item->setTextAlignment(Qt::AlignRight);
			}
			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}
		row++;
	} 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
    ui.lineEdit->setFocus();
}

void QNormativKorekcija::on_pushButton_5_clicked()
{
	pressEscape();
}

void QNormativKorekcija::pressF9()
{
	on_pushButton_4_clicked();
}

void QNormativKorekcija::on_pushButton_4_clicked()
{
	if (!validateProizvod())
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за производот е невалиден\nОдбери производ од листата на производи!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit->setFocus();
		return;
	}

	int mmid = m_id;
    int cols = model->columnCount();
    int rows = model->rowCount();
    if (!rows)
    {
        return;
    }
    int mid=0;
	QSqlDatabase db = QSqlDatabase::database();
	db.transaction();	
	bool sqlStat = true;

	QSqlQuery query1;
    query1.clear();
    query1.prepare("delete from proizvodi_sostav where id_proizvod = :a0");
	query1.bindValue(":a0", proizvodID);	
	sqlStat = sqlStat && query1.exec();
	QSqlError err = query1.lastError();
	

    QSqlQuery query;
    for (int i = 0; i < rows; i++)
    {
		QString mArtikalId = model->item(i, 0)->text();
		QString mArtikalKolicina = model->item(i, 4)->text();
		query.clear();
		query.prepare(
			"insert into proizvodi_sostav(id_proizvod, id_artikal, kolicina, firma_id) "
			"values(:a0,:a1,:a2, 0)"
			);
		query.bindValue(":a0", proizvodID);	
		query.bindValue(":a1", mArtikalId);	
		query.bindValue(":a2", mArtikalKolicina);	
		sqlStat = sqlStat && query.exec();
		QSqlError err = query.lastError();
	}
	if (sqlStat)
	{
		db.commit();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Нормативот е успешно корегиран."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		pressEscape();
	}
	else
	{
		db.rollback();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Нормативот НЕ Е корегиран !!!."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
	}
}
bool QNormativKorekcija::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from dokumenti where dok_tip = 40 and dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QNormativKorekcija::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::FocusIn)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: yellow");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }

	}
	if (event->type() == QEvent::FocusOut)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: none");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }
	}

	return false;
}

void QNormativKorekcija::on_plineEdit3_Pressed()
{
    ui.lineEdit_4->setFocus();
}
void QNormativKorekcija::on_plineEdit4_Pressed()
{
    on_pushButton_3_clicked();
}
void QNormativKorekcija::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);
    QModelIndex index;
    QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
    index = indexes.at(0);	// To get the row/column numbers use 
    if (index.column() > 3)
    {
        ui.tableView->openPersistentEditor(index);
    }
    indexPrev = index;
}

void QNormativKorekcija::closeEditor()
{
    ui.tableView->closePersistentEditor(indexPrev);
}

bool QNormativKorekcija::validateKomintent()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isKomintentExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}

bool QNormativKorekcija::validateProizvod()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isArtikliExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}